<template>
  <div class="login">
    <van-nav-bar
      class="login-navBar"
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="goBack"
    />
    <div class="login-panel">
      <van-field
        required
        label="用户名"
        label-align="center"
        v-model="userName"
        @input="checkUserName"
        :error-message='userNameErrorMsg'
        clearable
      />
      <van-field
        :type="pwdInputType"
        required
        label="密码"
        label-align="center"
        :right-icon="pwdIcon"
        v-model="password"
        @input="checkPassword"
        :error-message='passwordErrorMsg'
        @click-right-icon="changePwdInputType"
      />
      <div class="login-button">
        <van-button type="primary" size="large" @click="registerUser" :loading="openLoading" loading-text="请稍等...">登录</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from '@/axios/axios.js';
  export default {
    data() {
      return {
        userName: '',
        password: '',
        userNameErrorMsg: '',   // 用户名不规范时的提示文字，这个变量为空时，自动隐藏提示文字
        passwordErrorMsg: '',
        pwdInputType: 'password',   // 密码输入框的类型，控制密码显示与隐藏
        pwdIcon: 'closed-eye',    // 密码输入框的图标
        openLoading: false,   // 是否显示注册按钮加载中的状态。
      }
    },
    created() {
      if (localStorage.userInfo) {
        this.$toast.success('您已经登录')
        this.$router.push('/')
      }
    },
    methods: {
      goBack() {    // 左上角，返回按钮的事件
        this.$router.go(-1);
      },
      registerUser() {
        this.checkForm() && this.axiosLoginUser()   // 如果第一个为false，则后面的不会执行
      },
      axiosLoginUser() {    // 使用axios，向后台发起用户注册的请求
        this.openLoading = true;
        axios.ajax({
          method: 'POST',
          url: this.$url.user.login,
          data: {
            userName: this.userName,
            password: this.password,
          }
        }).then(res => {
          this.openLoading = false;
          if (res.message===true) {   // 密码匹配正确时，登录成功
            new Promise((resolve, reject) => {
              localStorage.userInfo = JSON.stringify({userName:this.userName, password:this.password})
              setTimeout(()=>{ resolve() }, 500);    // 等待500ms，让userInfo写入localStorage
            }).then(() => {
              this.$toast.success('登录成功')
              this.$router.push('/')
            }).catch(() => {
              Toast.fail('登录状态保存失败')
              console.log(err)
            })
          } else if(res.message===false) {
            this.$toast.fail('密码错误')
          } else {
            this.$toast.fail('用户名不存在')
          }
        }).catch(err => {   // 后台查询出错时
          this.openLoading = false;
          this.$toast.fail('登录失败')
        })
      },
      changePwdInputType() {  // 密码输入框，左侧眼睛图标点击时的事件
        this.pwdInputType = this.pwdInputType==='password' ? 'text' : 'password';
        this.pwdIcon = this.pwdIcon==='closed-eye' ? 'eye-o' : 'closed-eye';
      },
      checkForm() {   // 检验用户名和密码是否规范
        return !(this.checkUserName() || this.checkPassword())
      },
      checkUserName() {
        this.userNameErrorMsg = this.userName.trim().length < 5 ? '用户名不能少于5位' : '';
        return this.userNameErrorMsg.length;
      },
      checkPassword() {
        this.passwordErrorMsg = this.password.trim().length < 6 ? '密码不能少于6位' : '';
        return this.passwordErrorMsg.length;
      }
    }
  }
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/common.styl';
.login {
  background-color: $colorB;
}

// 用户注册的导航条
.login-navBar {
  /deep/ .van-nav-bar__title{
    font-weight: 600;
  }
}

// 用户注册的面板
.login-panel {
  margin-bottom: 3.125rem;
  margin-top: 1.25rem;
  padding: 0 0.625rem;
  .login-button {
    margin-top: 0.625rem;
  }
}
</style>